//
//  JinTabBar.swift
//  微博项目
//
//  Created by admin on 16/3/1.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class JinTabBar: UIView {
    
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
    // Drawing code
    }
    */
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(patternImage: UIImage(imageLiteral: "tabbar_background"))
    }
    func addButtons(tabbars:[Tabbar])
    {
        for var i = 0;i < tabbars.count;i++
        {
            let button = TabbarButton(tabbar: tabbars[i])
            if i == 0
            {
                button.selected  = true
            }
            button.tag = i + 1
            button.addTarget(self, action: Selector("tabbarButtonClick:"), forControlEvents: UIControlEvents.TouchDown)
            self.addSubview(button)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        let buttonW = self.frame.size.width / CGFloat(self.subviews.count)
        
        for var i = 0;i < self.subviews.count;i++
        {
            var j = i
            if i > 1
            {
                j += 1
            }
            self.subviews[i].frame = CGRectMake(buttonW * CGFloat(j), 0, buttonW, self.frame.size.height)
        }
        if (self.subviews.indexOf(self.button) == nil)
        {
            self.addSubview(self.button)
        }
        //
        self.button.frame = CGRectMake(buttonW * CGFloat(2), 0, buttonW, self.frame.size.height)
    }
    lazy var button:UIButton = {
        let temp = UIButton()
        temp.setBackgroundImage(UIImage(imageLiteral: "tabbar_compose_button"), forState: UIControlState.Normal)
        temp.setBackgroundImage(UIImage(imageLiteral: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        temp.setImage(UIImage(imageLiteral: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        temp.setImage(UIImage(imageLiteral: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        temp.addTarget(self, action: "sendMessage", forControlEvents: UIControlEvents.TouchDown)
        return temp
    }()
    func sendMessage()
    {
        self.tabbarButtonDelegate?.sendStatusButtonClick?()
    }
    weak var tabbarButtonDelegate:JinTabBarDelegate?
    weak var selectedButton:TabbarButton?
    func tabbarButtonClick(button:TabbarButton)
    {
        button.selected = true
        self.selectedButton?.selected = false
        self.selectedButton = button
        self.tabbarButtonDelegate?.tabbarButtonClick?(button.tag - 1)
    }
}
@objc protocol JinTabBarDelegate
{
    optional func tabbarButtonClick(index:Int)
    optional func sendStatusButtonClick()
}
